package com.yingxin.yxerp.module.permission.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.yingxin.yx.framework.commons.exception.BizException;
import com.yingxin.yx.framework.user.dto.PermissionDto;
import com.yingxin.yxerp.module.permission.entity.Permission;
import com.yingxin.yxerp.module.permission.mapper.PermissionMapper;
import com.yingxin.yxerp.module.permission.service.IPermissionService;
import com.yingxin.yxerp.module.permission.vo.req.PermissionCreateVo;
import com.yingxin.yxerp.module.permission.vo.req.PermissionQueryVo;
import com.yingxin.yxerp.module.permission.vo.req.PermissionUpdateVo;
import com.yingxin.yxerp.module.permission.vo.req.helper.PermissionManagerTreeHelper;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * 权限表 前端控制器
 * @author fanchao
 * @since 2021-05-10
 */

@RestController
@RequestMapping("/permission")
public class PermissionController {

    @Autowired
    private IPermissionService permissionService;

    @Autowired
    @SuppressWarnings("all")
    private PermissionMapper permissionMapper;

    @ApiOperation("权限列表")
    @GetMapping("/list")
    public List<PermissionDto> list() {
        List<PermissionDto> permissions = permissionMapper.listDto();
        return PermissionManagerTreeHelper.build(permissions);
    }

    @ApiOperation("查询 by id")
    @GetMapping("/{id}")
    public PermissionDto get(@PathVariable("id") String id) {
        Permission permission = permissionService.getById(id);
        PermissionDto dto = new PermissionDto();
        BeanUtil.copyProperties(permission, dto);
        return dto;
    }

    @ApiOperation(value = "新增下级")
    @PostMapping
    public void add(@RequestBody @Valid PermissionCreateVo createVo) {
        String parentId = createVo.getId();
        Permission parent;
        if ("0".equals(parentId)) {
            parent = new Permission();
            parent.setId("0");
            parent.setLevel("0");
        } else {
            parent = permissionService.getById(parentId);
            if (parent == null) {
                throw new BizException(String.format("不存在%s", parentId));
            }
        }
        String id;
        List<Permission> childrenList = permissionService.listByParentId(parentId);
        if (CollectionUtil.isNotEmpty(childrenList)) {
            Integer max = null;
            for (Permission p : childrenList) {
                if (p.getName().equals(createVo.getName())) {
                    throw new BizException(String.format("已存在%s", createVo.getName()));
                }
                int var1 = Integer.parseInt(p.getId());
                if (max == null || max < var1) {
                    max = var1;
                }
            }
            id = String.valueOf(max + 1);
        } else {
            id = parentId + "01";
        }
        Permission permission = new Permission();
        permission.setId(id);
        permission.setName(createVo.getName());
        permission.setType(createVo.getType());
        permission.setLevel(String.valueOf(Integer.valueOf(parent.getLevel()) + 1));
        permission.setParentId(parentId);
        permission.setStatus("1");
        permission.setSort( createVo.getSort() );
        permission.setPermissionString(createVo.getPermissionString());
        permission.setIcon(createVo.getIcon());
        permission.setUrl(createVo.getUrl());
        permissionService.save(permission);
    }

    @ApiOperation(value = "修改")
    @PutMapping
    public void update(@RequestBody @Valid PermissionUpdateVo updateVo) {
        Permission permission = permissionService.getById(updateVo.getId());
        if (permission == null) {
            throw new BizException(String.format("不存在%s", updateVo.getName()));
        }
        permission.setId(updateVo.getId());
        permission.setName(updateVo.getName());
        permission.setType(updateVo.getType());
        permission.setLevel(updateVo.getLevel());
        permission.setParentId(updateVo.getParentId());
        permission.setStatus("1");
        permission.setSort( updateVo.getSort() );
        permission.setPermissionString(updateVo.getPermissionString());
        permission.setIcon(updateVo.getIcon());
        permission.setUrl(updateVo.getUrl());
        permissionService.updateById(permission);
    }

    @ApiOperation(value = "删除")
    @DeleteMapping("/{id}")
    public void delete(@PathVariable("id") String id) {
        Permission permission = permissionService.getById(id);
        permissionService.removeById(id);
    }

    @ApiOperation(value = "递归删除")
    @DeleteMapping("/recursion/{id}")
    public void forceDelete(@PathVariable("id") String id) {
        Permission permission = permissionService.getById(id);
        recursion(permission);
    }

    @ApiOperation(value = "递归")
    public void recursion(Permission permission){
        List<Permission> permissions = permissionService.listByParentId(permission.getId());
        if (permissions != null){
            for (Permission permission1 : permissions) {
                recursion(permission1);
            }
        }else {
            permissionService.removeById(permission.getId());
        }

    }

    @ApiOperation(value = "验证指定 user id 是否存在 permission_string 权限")
    @PostMapping("/check/userid/permissionstring")
    public boolean add(@RequestBody @Valid PermissionQueryVo queryVo) {
        return permissionService.checkPermissionByUserIdAndPermissionString( queryVo );
    }

}